<template>
	<view class="content">

		<view class="content  gui-padding">
			<view class="gui-h4 gui-color-black gui-padding">医疗互助金缴费</view>
			
			<view class="gui-border-radius-large gui-padding" style="box-shadow: 3rpx 3rpx 3rpx #ccc;border: solid 1rpx #ccc; background-color: rgba(255, 255, 255, 0.6);">
				医疗互助金是一种由地方政府或权威组织推出的公益性保险，旨在为参保人员提供额外的医疗保障。‌
			</view>
			<view class="details gui-padding" style="box-shadow: 3rpx 3rpx 3rpx #ccc;border: solid 1rpx #ccc; background-color: rgba(255, 255, 255, 0.6);">
				<view class="fs-36 gui-color-black1" style="line-height:2rem;">
					<view class="d-flex-sb">缴费项目: <text>{{mutual_aid_money.title}}</text></view>
					<view class="d-flex-sb">缴费商户: <text>{{mutual_aid_money.commercial_tenant}}</text></view>
					<view class="d-flex-sb">应缴金额:<text> {{mutual_aid_money.total}}元</text></view>
					<view class="d-flex-sb">已缴次数:<text>{{mutual_aid_money.count}}次 / 3次</text></view>
					<view class="d-flex-sb">已缴金额:<text>{{mutual_aid_money.sum}}元</text></view>
					<view class="d-flex-sb">还需缴费:<text>{{mutual_aid_money.y_sum}}元</text></view>
				</view>

				<view class="word gui-margin-top" v-if="mutual_aid_money.y_sum>0">
					请选择支付金额:
				</view>
				<view v-if="mutual_aid_money.y_sum>0" class="gui-flex gui-wrap "
					style="gap:30rpx;justify-content: center">
					<view class=" gui-padding-small fs-50 gui-color-red "
						v-for="(item, idx) in mutual_aid_money.payment_amount" :key="idx">
						<view class="gui-border gui-box-shadow gui-padding-small gui-border-radius-large "
							:class="this_index == item.num ? 'gui-bg-red gui-color-white' : 'gui-bg-white'"
							@tap="hzj_money(item)">
							￥{{item.num}}
						</view>
					</view>
				</view>
			</view>

			<view v-if="mutual_aid_money.y_sum>0 && fee_status==1"
				style="line-height: 3rem; box-shadow: 3rpx 3rpx 3rpx #ccc;border: solid 1rpx #ccc; background-color: rgba(255, 255, 255, 0.6);padding: 15rpx 20rpx;"
				class="gui-color-black2 gui-border-radius-large gui-margin-top">
				<text style="color: rgba(0, 0, 0, 0.8);">请选择支付方式:</text>
				<gui-radio v-if="payTypes.wx" class="pay_type" :checked="payType=='wx'" @change="payType='wx'">
					<view class="gui-flex gui-align-items-center" style="gap: 20rpx; margin: 10rpx 0;">
						<image mode="aspectFit" class="pay_icon" src="../../static/pay/new/wxzf.png" />微信支付
					</view>
				</gui-radio>
				<gui-radio v-if="payTypes.abcBridge" class="pay_type" :checked="payType=='abcBridge'"
					@change="payType='abcBridge'">
					<view class="gui-flex gui-align-items-center" style="gap: 20rpx; margin: 10rpx 0;">
						<image class="pay_icon" src="../../static/pay/new/wjf.png" />微缴费
					</view>
				</gui-radio>
				<gui-radio v-if="payTypes.app" class="pay_type" :checked="payType=='app'" @change="payType='app'">
					<view class="gui-flex gui-align-items-center" style="gap: 20rpx; margin: 10rpx 0;">
						<image class="pay_icon" src="../../static/pay/new/nhzy.png" />农行掌银
					</view>
				</gui-radio>
			</view>

			<view class="gui-margin-top gui-padding" v-if="mutual_aid_money.y_sum>0 && fee_status==1">
				<button type="default"
					class="gui-button gui-gtbg-blue gui-box-shadow gui-noborder gui-border-radius-large"
					style="height: 100rpx;">
					<text class="gui-color-white gui-button-text gui-h3" style="line-height: 100rpx"
						@click="create_order">
						立即缴费(￥{{money}}元)
					</text>
				</button>


			</view>
			<view v-if="fee_status==0"  class="text-center gui-color-red gui-bold gui-margin gui-bg-white gui-padding  gui-border-radius-large gui-margin-top">
				{{fee_msg||'缴费暂停'}}
			</view>

			<!-- 历史账单查询按钮 -->
			<view class="gui-flex gui-space-between gui-align-items-center gui-padding gui-margin-top">
				<view class="gui-h4 gui-color-black">历史账单查询</view>
				<button type="default" size="mini" class="gui-bg-blue gui-color-white" @click="showHistory = !showHistory">
					{{showHistory ? '隐藏' : '查看'}}历史账单
				</button>
			</view>
			
			<!-- 历史账单查询区域 -->
			<view v-if="showHistory" class="gui-margin-bottom gui-padding gui-border-radius-large"
				style="box-shadow: 3rpx 3rpx 3rpx #ccc;border: solid 1rpx #ccc; background-color: rgba(255, 255, 255, 0.8);">
				<view class="gui-h5 gui-color-black gui-margin-bottom">历史账单查询</view>
				<view class="gui-flex gui-space-between gui-align-items-center gui-margin-bottom">
					<view class="gui-flex gui-align-items-center">
						<text class="gui-color-gray" style="font-size: 25rpx; margin-right: 10rpx;">开始日期:</text>
						<uni-datetime-picker start="2020-01-01" ref="ref_datePicker1" type="date" :clear-icon="false"
							v-model="historyQuery.start_date" @change="changeHistoryDate1" />
					</view>
					<view class="gui-flex gui-align-items-center">
						<text class="gui-color-gray" style="font-size: 25rpx; margin-right: 10rpx">结束日期:</text>
						<uni-datetime-picker ref="ref_datePicker2" type="date" :clear-icon="false"
							v-model="historyQuery.end_date" @change="changeHistoryDate2" />
					</view>
				</view>
				<view class="gui-flex gui-space-between">
					<button type="default" size="mini" class="gui-bg-green gui-color-white" @click="getHistoryData">
						查询历史
					</button>
					<!-- <button type="default" size="mini" class="gui-bg-orange gui-color-white" @click="exportHistory">
						导出记录
					</button> -->
				</view>
				
				<!-- 历史记录显示 -->
				<view v-if="historyList.length > 0" class="gui-margin-top">
					<view class="gui-h5 gui-color-black gui-margin-bottom">缴费历史（按时间倒序）</view>
					<view v-for="(item, index) in historyList" :key="'history-'+index"
						class="gui-flex gui-space-between gui-align-items-center gui-border-b gui-padding-small">
						<view style="width: 100rpx;display: flex;align-items: center;justify-content: center;">
							<image :src="getPayIcon(item.pay_type)" style="width: 40rpx;height: 40rpx;" mode="widthFix">
							</image>
						</view>
						<view class="gui-padding-small" style="flex: 1;line-height: 35rpx;">
							<view class="gui-color-black gui-h6">
								{{item.name}}(医疗互助金)
							</view>
							<view class="gui-color-gray gui-h6">
								缴费时间: {{item.pay_time}}
							</view>
							<view class="gui-color-blue gui-h6">
								支付方式: {{getPayTypeText(item.pay_type)}}
							</view>
						</view>
						<view class="gui-padding-small" style="width: 140rpx;text-align: right;">
							<view class="gui-color-red gui-h6 gui-bold">
								￥{{item.amount}}
							</view>
							<view class="gui-color-green gui-h6 gui-padding-small gui-border-radius-small status-text">
								缴费成功
							</view>
						</view>
					</view>
				</view>
				<view v-else-if="historySearched" class="gui-text-center gui-color-gray gui-margin-top">
					暂无历史记录
				</view>
			</view>

		</view>
	</view>
</template>

<script>
	import menuBar from "./menu_bar"
	export default {
		components: {
			menuBar
		},
		data() {
			return {
				// 互助金数据
				payType: "",
				payTypes: {
					wx: false,
					app: false,
					abcBridge: false
				},
				fee_status:1,
				fee_msg:'',
				payConfig: null,
				feeitem: null,
				mutual_aid_money: {
					title: '', // 名称
					commercial_tenant: '', // 缴费商户
					total: '', // 全部应缴金额
					count: '0', // 已经缴费了几次
					sum: '0', // 之前一共缴了多少
					y_sum: 0, // 还需要缴多少
					// 支付金额选择
					payment_amount: [{
						"num": '2000'
					}, {
						"num": '3000'
					}, {
						"num": '5000'
					}, {
						"num": '10000'
					}],
				},
				this_index: null,
				money: null,
				order_no: null,
				current: null,
				show: false,
				
				// 历史账单查询相关
				showHistory: false,
				historyList: [],
				historySearched: false,
				historyQuery: {
					start_date: '',
					end_date: ''
				}
			}
		},
		onShow() {
			// 初始化历史查询日期
			const today = new Date();
			const year = today.getFullYear();
			const month = today.getMonth() + 1;
			const day = today.getDate();
			this.historyQuery.start_date = `${year}-01-01`;
			this.historyQuery.end_date = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
			
			this.get_data();
		},
		methods: {
			get_data() {
				let self = this;
				this.payType = "";
				this.payTypes.wx = false;
				this.payTypes.app = false;
				this.payTypes.abcBridge = false;
				this.$boya.NGet('/app/hzj/query', null, function(res) {
					console.log("res", res);
					let _feeitem = res.data.feeitem;
					self.fee_status=res.data.feeitem.status;
					if(res.data.feeitem.msg){
						self.fee_msg=res.data.feeitem.msg;
					}
					self.payConfig = _feeitem.pay_mch_config;
					_feeitem.pay_types = _feeitem.pay_types.split(",");
					_feeitem.pay_types.forEach(d => {
						if (d == "农行支付") {
							self.payTypes.app = true;
						} else if (d == "微信支付") {
							self.payTypes.wx = true;
						} else if (d == "微缴费") {
							self.payTypes.abcBridge = true;
						}
					})
					self.mutual_aid_money.title = _feeitem.name;
					self.mutual_aid_money.commercial_tenant = _feeitem.pay_mch_config.name
					self.mutual_aid_money.count = res.data.hzj.length;
					self.mutual_aid_money.sum = res.data.sum;
					self.mutual_aid_money.total = res.data.total;
					// self.mutual_aid_money.payment_amount = [];

					self.mutual_aid_money.y_sum = res.data.total - res.data.sum
					if (res.data.hzj.length == 2) {
						self.mutual_aid_money.payment_amount = [];
						self.mutual_aid_money.payment_amount.push({
							num: self.mutual_aid_money.y_sum
						});
					}
					//  else {
					// 	self.mutual_aid_money.payment_amount.map(d => {
					// 		self.mutual_aid_money.payment_amount.push({
					// 			num: d
					// 		})
					// 	});
					// }
					self.feeitem = _feeitem;
					console.log(_feeitem);


				}, function(err) {
					console.log("erro", err);
				})
			},
			create_order() {
				let self = this;
				if(self.money == null){
					uni.showToast({
						title: "请选择支付金额",
						icon: 'error'
					})
					return;
				} else if (self.payType == "") {
					uni.showToast({
						title: "请选择支付类型",
						icon: 'error'
					})
					return;
				}
				this.$boya.NPost("/app/hzj/create_order", {
					pay_type: this.payType,
					money: this.money,
					feeitem_id: this.feeitem.id
				}, function(res) {
					console.log("create_order", res)
					self.order_no = res.data.order_no;

					self.to_pay(res.data);
				}, function(err) {
					console.log(err);
				})
			},
			hzj_money(item) {
				let num = Number(item.num)
				let money = Number(this.mutual_aid_money.y_sum)
				if (num > money) {
					this.$boya.msg('所选金额超过需支付金额，请重新选择');
				} else {
					this.this_index = item.num;
					this.money = item.num
					console.log(this.money)
				}
			},
			change_payType(text) {
				this.current = text;
				console.log("选择支付方式", this.current);
			},
			to_pay(data) {

				let ids = [];
				let self = this;
				//默认柳钢小程序
				let res = {
					data: data,
					type: this.payType
				}
				res.data.mch_id = self.payConfig.mch_id
				res.data.type = self.payType;
				res.data.app_id = "gh_edf4ceb10043";
				res.data.app_path = "pages/jf/pay?order_no=" + data.order_no;

				if (self.payType == "") {
					uni.showToast({
						title: "请选择支付类型",
						icon: 'error'
					})
					return;
				}
				if (self.payType == "abcBridge") {
					//农行微缴费
					res.data.app_id = "gh_a6986a2f785e";
					//res.data.app_path = "page/containers/payment/query-input/query-input?code=" + res.data.code;
					
					let user=uni.getStorageSync("userInfo");
					let path = "page/containers/payment/query-input/query-input?code=" + res.data
						.code;							
					path=path+"&userInput="+encodeURIComponent(JSON.stringify({input1:user.id_no,input2:user.real_name}));
					res.data.app_path=path;
					
				}
				console.log("to_pay->res", res);


				console.log(res);
				uni.navigateTo({
					url: "/pages/pay/pay_info?data=" + encodeURIComponent(JSON.stringify(res)),
					fail(err) {
						console.log(err);
					}
				})

			},
			
			// 历史账单查询相关方法
			changeHistoryDate1(e) {
				this.historyQuery.start_date = e;
				this.$refs.ref_datePicker1.close();
			},
			changeHistoryDate2(e) {
				this.historyQuery.end_date = e;
				this.$refs.ref_datePicker2.close();
			},
			getHistoryData() {
				let self = this;
				let parm = {
					"page": 1,
					"limit": 50,
					"type": "hzj",
					"status": 1 // 只查询缴费成功的
				};
				
				if (this.historyQuery.start_date != '') {
					parm.start_date = this.historyQuery.start_date;
				}
				if (this.historyQuery.end_date != '') {
					parm.end_date = this.historyQuery.end_date;
				}
				
				uni.showLoading({
					title: '查询中...'
				});
				
				this.$boya.NGet("/app/pay/order_list", parm, function(res) {
					console.log('医疗互助金历史记录: ', res);
					uni.hideLoading();
					self.historySearched = true;
					
					if (res.data && Array.isArray(res.data)) {
						// 按时间倒序排序，只显示缴费成功的记录
						self.historyList = res.data
							.filter(item => Number(item.pay_status) === 1)
							.sort((a, b) => new Date(b.pay_time) - new Date(a.pay_time));
						
						// 处理支付状态显示
						self.historyList.forEach(item => {
							item.pay_status_text = self.getPayStatusText(item.pay_status);
							item.pay_type_text = self.getPayTypeText(item.pay_type);
						});
					} else {
						self.historyList = [];
					}
				}, function(err) {
					console.log('获取医疗互助金历史记录失败: ', err);
					uni.hideLoading();
					self.historySearched = true;
					self.historyList = [];
					uni.showToast({
						title: '查询失败',
						icon: 'error'
					});
				});
			},
			exportHistory() {
				if (this.historyList.length === 0) {
					uni.showToast({
						title: '暂无数据可导出',
						icon: 'none'
					});
					return;
				}
				
				// 导出功能实现
				let exportData = this.historyList.map(item => ({
					缴费时间: item.pay_time,
					缴费金额: `￥${item.amount}`,
					支付方式: this.getPayTypeText(item.pay_type),
					缴费状态: '缴费成功'
				}));
				
				// 这里可以调用导出API或生成文件
				console.log('导出数据:', exportData);
				uni.showToast({
					title: '导出功能开发中',
					icon: 'none'
				});
			},
			getPayIcon(payType) {
				switch (payType) {
					case 'wx':
						return '../../static/homePage/wx.png';
					case 'abcBridge':
						return '../../static/homePage/xcx.png';
					case 'OPEN':
						return '../../static/homePage/xcx.png';
					case 'app':
						return '../../static/homePage/nh.png';
					default:
						return '../../static/homePage/wx.png';
				}
			},
			getPayTypeText(payType) {
				switch (payType) {
					case 'wx':
						return '微信支付';
					case 'abcBridge':
						return '微缴费';
					case 'OPEN':
						return '微缴费';
					case 'app':
						return '农行掌银';
					default:
						return '未知方式';
				}
			},
			getPayStatusText(status) {
				switch(Number(status)) {
					case 1:
						return '缴费成功';
					case 0:
						return '处理中';
					case -1:
						return '缴费失败';
					default:
						return '未知状态';
				}
			}

		}
	}
</script>

<style scoped lang="scss">
	.content {
		width: 100vw;
		height: 100vh;
		background: url('../../static/pay/new/bj1.png') 100% 100% / 100% 100%;
	}

	.synopsis {
		margin: 0 auto;
		border: 1rpx solid #999999;
		border-radius: 20rpx;
		text-indent: 2em;
		/* 2个字符的宽度 */
		margin-top: 40rpx;
	}

	.details {
		margin: 0 auto;
		border-radius: 20rpx;
		margin-top: 30rpx;
	}

	.word {
		color: #3B3B3B;
		font-size: 35rpx;
		line-height: 60rpx;
		// font-weight: bold;
	}

	.ylhzj {
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: space-evenly;
		margin-top: 10rpx;
		padding-bottom: 30rpx;
	}

	.huzhujin>view {
		text-align: center;
		height: 60rpx;
		line-height: 60rpx;
		padding: 6rpx 22rpx;
		font-size: 30rpx;
		font-weight: bold;
		border-radius: 15rpx;
	}

	.this_bg {
		background-color: #808080;
		color: #fff;
		box-shadow: 15rpx 15rpx 20rpx #7F7F7F;
		border: 2px solid #000;
	}

	.defu_bg {
		color: #000;
		background-color: white;
		border: 1px solid #000;
	}

	.goPayFees {

		margin: 0 auto;
		margin-top: 30rpx;
		border-radius: 20rpx;

		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.bill {
		font-weight: bold;
		font-size: 40rpx;
	}

	.goTo {
		color: #F9F4AF;
		font-size: 35rpx;
		padding: 10rpx 15rpx;
		border-radius: 25rpx;
		border: 1px solid black;
		background-color: #B50B10;
	}

	.guimodal_payment {
		position: absolute;
		bottom: 0;
		background-color: white;
		border-radius: 15rpx 15rpx 0 0;
		z-index: 999;
		border-top: 2px solid #D8D8D8;
	}

	.pop {
		width: 100vw;
		height: 650rpx;
	}

	.pay_title {
		padding-top: 30rpx;
		font-size: 35rpx;
		text-align: center;
		font-weight: bold;
	}

	.money {
		margin-top: 35rpx;
		margin-left: 50rpx;
	}

	.way {
		margin-top: 35rpx;
		margin-left: 50rpx;
	}

	.forr {
		display: flex;
		justify-content: space-around;
		padding-top: 25rpx;
		padding-bottom: 30rpx;
	}

	.box2 {
		width: 150rpx;
		height: 180rpx;
		border-radius: 15rpx;
	}

	.golden {
		border: 3px solid #D4D0C9;
		background-color: #FEF9F2;
	}

	.black {
		border: 1px solid #D4D0C9;
		background-color: #ffffff;
	}

	.logo1 {
		width: 90rpx;
		height: 80rpx;
		margin-left: 32rpx;
		margin-top: 30rpx;
		position: relative;
	}

	.logo2 {
		position: absolute;
		width: 100rpx;
		height: 100rpx;
		margin-top: 28rpx;
		margin-left: -90rpx;
	}

	.text {
		font-size: 25rpx;
		text-align: center;
		color: #000;
		margin-top: 10rpx;
	}

	.flexx {
		display: flex;
		margin-top: 15rpx;
		justify-content: space-around;
		border-top: 10px solid #D8D8D8;
		padding-top: 35rpx;
	}

	.confirm {
		width: 300rpx;
		height: 45rpx;
		line-height: 45rpx;
		border-radius: 50rpx;
		background: linear-gradient(to right, #5F5F5F, #3B3B3B);
		color: #EAD5B0;
		text-align: center;
		padding: 20rpx 0;
	}

	.cancel {
		width: 300rpx;
		height: 45rpx;
		line-height: 45rpx;
		border-radius: 50rpx;
		background: linear-gradient(to right, #c8c8c8, #c1c1c1);
		color: black;
		text-align: center;
		padding: 20rpx 0;
	}

	.pay_type {
		display: flex;
		align-items: center;
		gap: 20rpx;
		font-size: 1.2rem;
		padding: 10rpx 0;
		line-height: 50rpx;

		image {
			width: 60rpx;
			height: 60rpx;
			margin-right: 20rpx;
		}

		.gui-radio-lable {
			display: flex;
			align-items: center;
		}
	}

	.pay_icon {
		width: 30px;
		height: 30px;
	}
	
	.status-text {
		white-space: nowrap;
		font-size: 24rpx;
	}
</style>